package com.ming.multifunction.controller;

import com.ming.multifunction.common.BaseResponse;
import com.ming.multifunction.common.DeleteRequest;
import com.ming.multifunction.common.ErrorCode;
import com.ming.multifunction.common.ResultUtils;
import com.ming.multifunction.exception.BusinessException;
import com.ming.multifunction.model.domain.User;
import com.ming.multifunction.model.request.UpdateUserRequest;
import com.ming.multifunction.model.request.UserLoginRequest;
import com.ming.multifunction.model.request.UserRegisterRequest;
import com.ming.multifunction.model.vo.UserVO;
import com.ming.multifunction.service.UserService;
import com.ming.multifunction.utils.Jmail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.MessagingException;

import static com.ming.multifunction.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Autowired
    private Jmail jmail;

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest,HttpServletRequest request) {
        // 校验
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUsername();
        String userPassword = userRegisterRequest.getUserPassword();
        String verifyCode = userRegisterRequest.getVerifyCode();

       /* if (StringUtils.isAnyBlank(userAccount, userPassword, verifyCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }*/
        if (StringUtils.isBlank(userAccount)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号不能为空");
        }
        if (StringUtils.isBlank(userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不能为空");
        }
        if (StringUtils.isBlank(verifyCode)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"验证码不能为空");
        }


        long result =userService.doRegister(userRegisterRequest, request);
        return ResultUtils.success(result);
    }

    /**
     * 获取验证码
     * @param userRegisterRequest
     * @param request
     * @return
     */
    @PostMapping("/getcode")
    public BaseResponse<Integer> getVerifyCode(@RequestBody UserRegisterRequest userRegisterRequest,HttpServletRequest request){

        String randomCode = userService.randomCode(request);
        String email = userRegisterRequest.getEmail();

        if (StringUtils.isBlank(email)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"邮箱不能为空");
        }
        String regex = "^([A-Za-z0-9_\\-\\.\\u4e00-\\u9fa5])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,8})$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(email);
        boolean isValid = matcher.matches();
        if (!isValid) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请填写有效的邮箱");
        }

        System.out.println(email);

        jmail.setToMail(email);
        jmail.setTopic("注册验证码");
        jmail.setContent(randomCode);
        System.out.println(randomCode);
        try {
            jmail.send();
            System.out.println(email);
            System.out.println("jmail.send执行");
            log.info("jmail.send执行");
        } catch (MessagingException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"邮箱发送失败！");
        }
        return ResultUtils.success(0);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUsername();
        String userPassword = userLoginRequest.getUserPassword();

        if (StringUtils.isBlank(userAccount)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号不能为空");
        }
        if (StringUtils.isBlank(userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不能为空");
        }

        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前用户
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        long userId = currentUser.getId();
        // TODO 校验用户是否合法
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);

        return ResultUtils.success(safetyUser);
    }

    /**
     * 删除用户
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        long id = deleteRequest.getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/update")
    private BaseResponse<Integer> updateUser(@RequestBody UpdateUserRequest user, HttpServletRequest request){

        if (user==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"更新信息不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        int res = userService.updateUser(user, loginUser);

        return ResultUtils.success(res);
    }

    /**
     * 获取所有用户
     *
     * @param request
     * @return
     */
    @GetMapping("/all")
    public BaseResponse<List<User>> getAllUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        boolean admin = userService.isAdmin(currentUser);

        if (!admin){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        List<User> userList = userService.list();
        if (CollectionUtils.isEmpty(userList)){
            return ResultUtils.success(new ArrayList<>());
        }


        return ResultUtils.success(userList);
    }


    /**
     * 变更用户权限
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/change")
    public BaseResponse<Boolean> changeUserRole(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        long id = deleteRequest.getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User modifyUser = userService.getById(id);
        if (modifyUser==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        int role = modifyUser.getUserRole();
        User user = new User();
        BeanUtils.copyProperties(modifyUser,user);

        user.setUserRole(role==0?1:0);
        boolean update = userService.updateById(user);

        if (!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"更新失败");
        }

        return ResultUtils.success(update);
    }

    /**
     * 根据关键词查询用户
     * @param searchText
     * @return
     */
    @GetMapping("/search")
    public BaseResponse<List<UserVO>> getPost(@RequestParam(required = false) String searchText){

        if (StringUtils.isBlank(searchText)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"搜索关键词不能为空");
        }
        List<UserVO> searchList=userService.searchUser(searchText);

        return ResultUtils.success(searchList);
    }


}
